package com.yunshipei.common.net.converter;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.yunshipei.common.net.ProgressRequestListener;
import com.yunshipei.common.net.ProgressResponseListener;

import java.io.IOException;

/**
 * Created by cike on 16/6/17.
 */
public class HttpClientHelper {

    public static OkHttpClient addProgressResponseListener(final ProgressResponseListener progressResponseListener) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressResponseListener))
                        .build();
            }
        });
        return client.build();
    }

    public static OkHttpClient addProgressRequestListener(final ProgressRequestListener progressRequestListener) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .method(original.method(), new ProgressRequestBody( original.body(), progressRequestListener))
                        .build();
                return chain.proceed(request);
            }
        });
        return client.build();
    }
}
